package com.ysucloud.users.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ysucloud.users.Utils.NetUtil;
import com.ysucloud.users.exception.wxException;
import com.ysucloud.users.service.LoginService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Description: users
 * Created by 刘翰文 on 2019/6/28 13:05
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Value("${WX.appid}")
    private String appid;

    @Value("${WX.appsecret}")
    private String appsecret;

    @Value("${WX.url}")
    private String url;

    @Autowired
    NetUtil netUtil;

    @Override
    public String getOpenId(String code) {
        String true_url = String.format(url,appid,appsecret,code);

        String ret = null;
        try {
            ret = netUtil.doGet(true_url);
        }catch (Exception e){
            throw new wxException("服务器连接失败！");
        }


        JSONObject jsonObject = JSON.parseObject(ret);
        String openid = jsonObject.getString("openid");

        if(StringUtils.isEmpty(openid)){
            throw new wxException(ret);
        }
        return openid;
    }
}
